package cn.codergege.kotlinbasics.controlflow

import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest

@SpringBootTest
class WhenDemoTest {

    /**
     *  演示 when 作为语句使用
     */
    @Test fun testWhen() {
        val a = 10
        when(a) {
            1 -> assertTrue(a == 1) // 只有简单一个表达式可以省略花括号
            3 -> { assertTrue(a == 3) }
            5 -> { println("a = $a") }
            else -> println("a > 5") // 作为语句时, 可以不写 else 的.
        }
    }

    /**
     *  演示 when 作为表达式
     */
    @Test fun testWhenExpr() {
        val a = 6
        val result = when(a) {
            1 -> "a == 1"
            3 -> {
                println(" a == $a")
                "a == 3"
            }
            5 -> { "a == 5" }
            else -> "a > 5"
        }
        assertEquals("a > 5", result)
    }

    @Test fun testWhenMerge() {
        val n = 2
        val result = when (n) {
            1, 2, 3 -> "x"
            4 -> "xx"
            else -> "xxx"
        }
        assertEquals("x", result)
    }

    @Test fun testWhenRange() {
        val n = 40
        val result = when (n) {
            in 1..10 -> 1
            in 11..20 -> 2
            in 21..30 -> 3
            in 31..40 -> 4
            in 41..50 -> 5
            else -> 10
        }
        assertTrue(result == 4)
    }

}